<template>
  <div>
    <el-drawer v-model="drawer" title="上传文件" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input v-model="ruleForm.title" clearable placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="文件类型：" prop="typeId">
          <el-select
            v-model="ruleForm.typeId"
            placeholder="请选择文件类型"
            style="width: 100%"
            filterable
            @change="handleDirChange($event)"
          >
            <el-option
              v-for="ite in typeList"
              :key="ite.id"
              :label="`${ite.type}—${ite.stage}`"
              :value="ite.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="文件：">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            action="#"
            :auto-upload="false"
            v-model:file-list="fileList"
            :on-change="changUpload"
            style="width: 280px"
          >
            <template #trigger>
              <el-button type="primary" icon="Upload" :disabled="fileList.length === 1">
                上传文件
              </el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { postFileDetail } from '@/api/controller/file-detail-controller/index'
  import { postFileTypeMatch } from '@/api/controller/file-type-controller/index'
  const drawer = ref(false)
  const typeList = ref([])
  const show = async (val, stage) => {
    ruleForm.value = {
      projectNumber: val,
      title: null,
      typeId: null,
      stage: null,
      remark: null,
    }
    fileList.value = []
    let res = await postFileTypeMatch({ stage: stage })
    typeList.value = res.data
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    projectNumber: null,
    title: null,
    typeId: null,
    stage: null,
    remark: null,
  })

  const rules = reactive({
    title: [
      { required: true, message: '请输入标题', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    typeId: [{ required: true, message: '请选择文件类型', trigger: 'blur' }],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        if (fileList.value[0]) {
          const file = new FormData()
          file.append('file', fileList.value[0].raw)
          const result = await postFileDetail(ruleForm.value, file, { loading: true })
          if (result.code === 200) {
            ElMessage.success('添加成功')
            emit('refresh')
            emit('getData')
            drawer.value = false
          } else {
            ElMessage.warning('上传失败')
          }
        } else {
          ElMessage.warning('请正确填写表单')
          return false
        }
      }
    })
  }
  const fileList = ref([])
  const changUpload = (file) => {
    const { name } = file
    if (!ruleForm.value.title) {
      ruleForm.value.title = name.substring(0, name.lastIndexOf('.'))
    }
  }
  const handleDirChange = (id) => {
    let dir = typeList.value.find((item) => item.id === id)
    ruleForm.value.stage = dir.stage
  }
  const emit = defineEmits(['refresh', 'getData'])
  defineExpose({
    show,
  })
</script>
